package cn.bandeqing.base.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;
    public static String HOST = "";

//    static {
//        try {
//            HOST = InetAddress.getLocalHost().getHostAddress();
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return context.getBean(requiredType);
    }

    public static String appName() {
        return context.getEnvironment().getProperty("spring.application.name");
    }

    /**
     * @return 返回当前 traceId logback MDC中获取
     */
    public static String traceId() {

        // old
//        Tracer tracer = getBean(Tracer.class);
//        TraceContext tc = tracer.currentTraceContext().context();
//        return ObjectUtil.isNull(tc) ? null : tc.traceId();

        return MDC.get("traceId");
    }

}
